package org.example.spring_security_demo1.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.stereotype.Service;

//@Configuration
public class MySecurityConfig {

    @Bean
    public UserDetailsService userDetailsService() {
        UserDetails user1 = User.builder().username("eric").password(passwordEncoder().encode("123456"))
                .roles("student")
                .authorities("student:add", "student:update", "student:delete")
                .build();
        UserDetails user2 = User.builder().username("tom").password(passwordEncoder().encode("123456"))
                .roles("teacher")
//                .authorities("teacher:add", "teacher:update", "teacher:delete")
                .build();

        InMemoryUserDetailsManager memoryUserDetailsManager = new InMemoryUserDetailsManager();
        memoryUserDetailsManager.createUser(user1);
        memoryUserDetailsManager.createUser(user2);
        return memoryUserDetailsManager;
    }
    @Bean
    public PasswordEncoder passwordEncoder() {
        return NoOpPasswordEncoder.getInstance();
    }

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
            http.
                    authorizeRequests(auth->{
                        auth
                                .antMatchers("/public/**","/login/**").permitAll()
                                .antMatchers("/teacher/**").hasRole("teacher")
                                .anyRequest().authenticated();

                    });
            http.formLogin((form)->{
                form.permitAll();
            });
            return http.build();

    }
}
